package com.rem.others.part1;

import com.rem.lambda.part1.Employee;
import org.junit.Test;

import java.util.Optional;

/**
 * Optional类
 *
 * @Author Rem
 * @Date 2020-02-14
 */

public class TestOptional {

    /**
     * Optional 容器类的常用方法
     * Optional.of(T t) :创建一个Optional 实例
     * Optional.empty() :创建一个空的Optional 实例
     * Optional.ofNullable(T t) :若t 不为null,创建Optional 实例，否则 创建空实例
     * isPresent() : 判断是否包含值
     * orElse(T t) : 如果调用对象包含值，返回该值，否则返回t
     * orElseGet(Suulier s) : 如果调用对象包含值，返回该值，否则返回s获取的值
     * map(Function f) : 如果有值对其处理，并返回处理后的Optional，否则返回Optional.empty()
     * flatMap(Function f) : 与map相似，返回值必须是Optional
     */


    @Test
    public void test() {
        Optional<Employee> optional = Optional.of(new Employee());
        Employee employee = optional.get();
        System.out.println(employee);

        // Optional<Employee> op = Optional.of(null); //报错
    }

    @Test
    public void test2() {
        Optional<Employee> optional = Optional.empty();
        //  System.out.println(optional.get());
    }

    @Test
    public void test3() {
        Employee employee = new Employee("张三", 13);

        Optional<Employee> optional = Optional.ofNullable(employee);
        if (optional.isPresent()) {
            System.out.println(optional);
        }
    }

    @Test
    public void test4() {
        Optional<Employee> optional = Optional.of(new Employee());
        Employee employee = optional.orElse(new Employee("张三", 13));
    }

    @Test
    public void test5() {
        Optional<Employee> optional = Optional.of(new Employee());
        optional.orElseGet(() -> new Employee("张三", 13));
        System.out.println(optional.get());
    }

    @Test
    public void test6() {
        Optional<Employee> optional = Optional.of( new Employee("张三", 13));
        Optional<String> s = optional.map(Employee::getName);
        System.out.println(s.get());
    }

    @Test
    public void test7() {
        Optional<Employee> optional = Optional.of( new Employee("张三", 13));
        Optional<Employee> optional1 = optional.flatMap(e -> Optional.of(new Employee(e.getName())));
        System.out.println(optional1.get());
    }

}
